import React, { useRef, useState, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { Select, Button, Modal, Message, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import moment from 'moment';
import { nanoid } from 'nanoid';
import request from '@/utils/request';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormDigit,
} from '@ant-design/pro-form';
import Track from './components/track';
import { StatisticCard } from '@ant-design/pro-components';
const { Divider } = StatisticCard;

export default (props) => {
  const actionRef = useRef();
  const [isAddVisible, setIsAddVisible] = useState(false);
  const [isEditVisible, setIsEditVisible] = useState(false);
  const [editRecord, setEditRecord] = useState({});

  const [isShowTrack, setIsShowTrack] = useState(false);
  const [status, setStatus] = useState([]);
  const [statusVlueEumn, setStatusVlueEumn] = useState({});
  const [filterStatus, setFilterStatus] = useState('');
  const [countInfo, setCountInfo] = useState({});
  const [responsive, setResponsive] = useState(false);
  const colors = ['#000', 'orange', 'blue', '#ccc', 'red', 'purple', 'green', 'yellow', '#1890ff'];

  const getStatusEumn = () => {
    request.post('/project/getAllProjectStatus').then((res) => {
      setStatus(res);
      const obj = {};
      res &&
        res.map((item) => {
          obj[item.value] = {
            text: item.name,
            status: item.value,
          };
        });
      setStatusVlueEumn(obj);
    });
  };

  const getProjectCount = () => {
    request.post('/project/projectCount').then((res) => {
      setCountInfo(res);
    });
  };

  useEffect(() => {
    getStatusEumn();
    getProjectCount();
  }, []);

  const onAddFinish = async (values) => {
    const res = await request.post('/project/saveProject', {
      data: {
        ...values,
      },
    });

    if (res.success) {
      Message.success('添加成功');
      setIsAddVisible(false);
      getProjectCount();
      actionRef.current.reload();
    } else {
      if (res.message) {
        Message.error(res.message);
      } else {
        Message.error('添加失败');
      }
    }
  };

  const onEditFinish = async (values) => {
    const res = await request.post('/project/updateProject', {
      data: {
        id: editRecord.id,
        ...values,
      },
    });

    if (res.success) {
      Message.success('编辑成功');
      setIsEditVisible(false);
      actionRef.current.reload();
    } else {
      if (res.message) {
        Message.error(res.message);
      } else {
        Message.error('编辑失败');
      }
    }
  };

  const handleRemove = (id) => {
    Modal.confirm({
      title: '确认',
      icon: <QuestionCircleOutlined />,
      content: '确认删除项目？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // const hide = message.loading('正在执行...');
        // hide();
        const res = await request.post('/project/removeProject', {
          data: {
            id,
          },
        });
        if (res.success) {
          message.success('删除成功！');
        } else {
          message.error('删除失败！');
        }
        actionRef.current.reloadAndRest();
      },
      onCancel: () => {
        // setIsEditVisible(false);
      },
    });
  };

  const columns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      // ellipsis: true,
    },

    {
      title: '金额',
      dataIndex: 'scale',
      key: 'scale',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '项目状态',
      dataIndex: 'status',
      key: 'status',
      hideInSearch: true,
      render: (item) => {
        return <span>{statusVlueEumn[item]?.text}</span>;
      },
      width: 100,
    },
    {
      title: '项目状态',
      dataIndex: 'status',
      key: 'status',
      // valueEnum: statusVlueEumn,
      hideInTable: true,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            allowClear
            onChange={(e) => {
              setFilterStatus(e);
            }}
            value={filterStatus}
            listHeight={300}
          >
            {status.map((option, index) => (
              <Select.Option key={option.value} value={option.value}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div
                    style={{
                      marginRight: 10,
                      background: colors[index],
                      width: 10,
                      height: 10,
                      borderRadius: '50%',
                      position: 'relative',
                    }}
                  >
                    <div
                      style={{
                        background: '#fff',
                        height: 5,
                        width: 5,
                        borderRadius: '50%',
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%,-50%)',
                      }}
                    ></div>
                  </div>
                  <span>{option.name}</span>
                </div>
              </Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      key: 'custName',
    },
    {
      title: '当前跟进人',
      dataIndex: 'chargePerson',
      key: 'chargePerson',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '重点事项',
      dataIndex: 'keyPoints',
      hideInSearch: true,
      key: 'keyPoints',
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      hideInSearch: true,
      key: 'remarks',
      hideInTable: true,
    },
    {
      title: '关联客户',
      dataIndex: 'relatedCusts',
      hideInSearch: true,
      key: 'relatedCusts',
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      hideInSearch: true,
      key: 'createAt',
      width: 200,
    },
    {
      title: '跟进力度',
      dataIndex: 'trackLevel',
      hideInSearch: true,
      key: 'trackLevel',
      width: 100,
      tip: `正常，判断依据为2周内有跟进记录;
      黄灯，判断依据为4周内有跟进记录（项目完成和商机终止的除外）;
      红灯，判断依据为4周多无跟进记录（项目完成和商机终止的除外）`,
      render: (text1, record, _, action) => {
        const fromNow = Math.abs(moment(record.createAt).diff(moment(), 'days'));

        // 如果两周内有记录
        let color = 'green';
        let text = '正常';
        if (fromNow <= 14 && record.trackingRecords?.length) {
          color = 'green';
          text = '正常';
        }

        if (
          fromNow <= 28 &&
          fromNow > 14 &&
          !record.trackingRecords?.length &&
          !['BUSINESS_TERMINATION', 'COMPLETE'].includes(record.trackingRecords.status)
        ) {
          color = 'yellow';
          text = '不足';
        } else if (
          fromNow > 28 &&
          !record.trackingRecords?.length &&
          !['BUSINESS_TERMINATION', 'COMPLETE'].includes(record.trackingRecords.status)
        ) {
          color = 'red';
          text = '严重不足';
        }
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div
              style={{
                width: 8,
                height: 8,
                background: color,
                borderRadius: '50%',
                marginRight: 10,
              }}
            ></div>
            <span>{text}</span>
          </div>
        );
      },
    },
    {
      title: '跟踪记录数',
      dataIndex: 'trackingRecords',
      hideInSearch: true,
      key: 'trackingRecords',
      width: 100,
      render: (text, record, _, action) => {
        return <span>{record.trackingRecords.length}</span>;
      },
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      width: 220,
      render: (text, record, _, action) => [
        <a
          key={nanoid()}
          onClick={() => {
            setEditRecord(record);
            setIsShowTrack(true);
          }}
        >
          跟进
        </a>,
        <a
          key="edit"
          onClick={() => {
            setEditRecord(record);
            setIsEditVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            handleRemove(record.id);
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const getModalFields = () => {
    const column = [
      {
        name: '项目名称',
        value: 'name',
        isRequired: true,
      },
      {
        name: '项目描述',
        value: 'desc',
        isRequired: true,
        textArea: true,
      },
      {
        name: '项目状态',
        value: 'status',
        isRequired: true,
        select: true,
      },
      {
        name: '客户名称',
        value: 'custName',
        isRequired: true,
      },
      {
        name: '项目体量(万)',
        value: 'scale',
      },
      {
        name: '当前跟进人',
        value: 'chargePerson',
      },
      {
        name: '关联客户',
        value: 'relatedCusts',
      },
      {
        name: '重点事项',
        value: 'keyPoints',
      },
      {
        name: '备注',
        value: 'remarks',
        textArea: true,
      },
    ];

    const arr = column.map((item) => {
      if (item.select) {
        return (
          <div key={Math.random()}>
            <ProFormSelect
              rules={[{ required: item.isRequired ? true : false, message: '请选择项目状态' }]}
              name="status"
              label="项目状态"
              placeholder="请选择项目状态"
            >
              <Select listHeight={300}>
                {status.map((option, index) => (
                  <Select.Option key={option.value} value={option.value}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <div
                        style={{
                          marginRight: 10,
                          background: colors[index],
                          width: 10,
                          height: 10,
                          borderRadius: '50%',
                          position: 'relative',
                        }}
                      >
                        <div
                          style={{
                            background: '#fff',
                            height: 5,
                            width: 5,
                            borderRadius: '50%',
                            position: 'absolute',
                            top: '50%',
                            left: '50%',
                            transform: 'translate(-50%,-50%)',
                          }}
                        ></div>
                      </div>
                      <span>{option.name}</span>
                    </div>
                  </Select.Option>
                ))}
              </Select>
            </ProFormSelect>
          </div>
        );
      } else if (item.textArea) {
        return (
          <div key={Math.random()}>
            <ProFormTextArea
              name={item.value}
              label={item.name}
              rules={[{ required: item.isRequired ? true : false, message: '请输入项目描述' }]}
            ></ProFormTextArea>
          </div>
        );
      } else if (item.value == 'scale') {
        return (
          <div key={Math.random()}>
            <ProFormDigit
              name={item.value}
              label={item.name}
              placeholder={`请输入${item.name}`}
              rules={
                item.isRequired && [
                  {
                    required: true,
                    message: `请输入${item.name}`,
                  },
                ]
              }
            />
          </div>
        );
      } else {
        return (
          <div key={Math.random()}>
            <ProFormText
              name={item.value}
              label={item.name}
              placeholder={`请输入${item.name}`}
              rules={
                item.isRequired && [
                  {
                    required: true,
                    message: `请输入${item.name}`,
                  },
                ]
              }
            />
          </div>
        );
      }
    });

    return arr;
  };

  return (
    <>
      <PageContainer style={{ display: isShowTrack ? 'none' : 'block' }} title={props.route.name}>
        {/* <div
          style={{
            background: '#fff',
            borderBottom: '1px solid #f2f2f2',
            padding: '10px 30px',
            fontWeight: 'bold',
            fontSize: 16,
            marginTop: 30,
          }}
        >
          <span>统计信息</span>
        </div>
        <div style={{ display: 'flex', marginBottom: 20, background: '#fff', padding: 15 }}>
          <div
            style={{
              width: 220,
              height: 80,
              background: '#fff',
              marginRight: 20,
              borderRadius: 15,
              padding: '8px 15px',
              position: 'relative',
            }}
          >
            <p style={{ marginBottom: 0 }}>
              <div
                style={{
                  width: 4,
                  height: 70,
                  background: '#000',
                  position: 'absolute',
                  left: 5,
                }}
              ></div>
              正在跟进:
              <span style={{ fontSize: 20, fontWeight: 'bold', color: '#000' }}>
                {countInfo.processCount}
              </span>
            </p>
            <span>
              累计项目金额:
              <span style={{ fontSize: 18, color: '#000', fontWeight: 'bold' }}>
                {countInfo.processMoney}
              </span>
              万元
            </span>
          </div>
          <div
            style={{
              width: 220,
              height: 80,
              background: '#fff',
              marginRight: 20,
              borderRadius: 15,
              padding: '8px 15px',
              position: 'relative',
            }}
          >
            <div
              style={{
                width: 4,
                height: 70,
                background: 'green',
                position: 'absolute',
                left: 5,
              }}
            ></div>
            售后维护:{' '}
            <span style={{ fontSize: 20, fontWeight: 'bold', color: 'green' }}>
              {countInfo.afterSalesCount}
            </span>
          </div>
          <div
            style={{
              width: 220,
              height: 80,
              background: '#fff',
              marginRight: 20,
              borderRadius: 15,
              padding: '8px 15px',
              position: 'relative',
            }}
          >
            <div
              style={{
                width: 4,
                height: 70,
                background: '#1890ff',
                position: 'absolute',
                left: 5,
              }}
            ></div>
            商机终止:{' '}
            <span style={{ fontSize: 20, fontWeight: 'bold', color: '#1890ff' }}>
              {countInfo.terminationCount}
            </span>
          </div>
        </div> */}
        <div
          style={{
            background: '#fff',
            borderBottom: '1px solid #f2f2f2',
            padding: '10px 30px',
            fontWeight: 'bold',
            fontSize: 16,
            marginTop: 30,
          }}
        >
          <span>统计信息</span>
        </div>
        <StatisticCard.Group>
          <StatisticCard
            statistic={{
              title: '正在跟进',
              // tip: '帮助文字',
              value: countInfo.processCount,
            }}
          />
          <StatisticCard
            statistic={{
              title: '累计项目金额(万元)',
              value: countInfo.processMoney,
            }}
          />
          <Divider />
          <StatisticCard
            statistic={{
              title: '售后维护',
              value: countInfo.afterSalesCount,
            }}
          />
          <StatisticCard
            statistic={{
              title: '商机终止',
              value: countInfo.terminationCount,
            }}
          />
        </StatisticCard.Group>
        <ProTable
          onReset={() => {}}
          pagination={{
            pageSize: 10,
          }}
          headerTitle="项目跟踪"
          columns={columns}
          actionRef={actionRef}
          rowSelection={false}
          cardBordered
          request={async (params = {}, sort, filter) => {
            const res = request.post('/project/list', {
              data: {
                pageNo: params.current,
                pageSize: params.pageSize,
                custName: params.custName,
                name: params.name,
                status: filterStatus,
              },
            });
            return res;
          }}
          editable={
            {
              // type: 'multiple',
            }
          }
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          dateFormatter="string"
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={(e) => setIsAddVisible(true)}
            >
              新建项目
            </Button>,
          ]}
        />
        {/* 新建型号 */}
        <ModalForm
          initialValues={{
            beyond: false,
          }}
          title="新建项目"
          width={500}
          visible={isAddVisible}
          onFinish={onAddFinish}
          onVisibleChange={(visible) => !visible && setIsAddVisible(false)}
          validateTrigger="onBlur"
          layout="horizontal"
          labelCol={{ span: 5 }}
          modalProps={{ destroyOnClose: true }}
        >
          {getModalFields()}
        </ModalForm>
        {/*  编辑型号*/}
        <ModalForm
          initialValues={editRecord}
          title="编辑项目"
          width={500}
          visible={isEditVisible}
          onFinish={onEditFinish}
          onVisibleChange={(visible) => !visible && setIsEditVisible(false)}
          validateTrigger="onBlur"
          layout="horizontal"
          labelCol={{ span: 5 }}
          modalProps={{ destroyOnClose: true }}
        >
          <div>{getModalFields()}</div>
        </ModalForm>
      </PageContainer>
      <div style={{ display: !isShowTrack ? 'none' : 'block' }}>
        <Track
          statusVlueEumn={statusVlueEumn}
          actionRef={actionRef}
          setIsShowTrack={setIsShowTrack}
          data={editRecord}
          status={status.map((item) => ({ label: item.name, value: item.value }))}
          getProjectCount={getProjectCount}
        ></Track>
      </div>
    </>
  );
};
